package com.rzjm.api.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.Tools;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: ZhouWei
 *@Description:  微信小程序模块
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/module")//url:模块/资源/{}/细分
public class WxModuleController extends BaseController {

    @Resource
    private WxModuleService moduleService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;

    /** 商家列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/list",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            int groupId = 0;
            if(sysUser.getGroupId()!=null){
                groupId = sysUser.getGroupId();
            }
            if(groupId == 0){
                groupId = 1;
            }
            List<WxModule> list = moduleService.getListByGroupId(groupId,user);
            map.put("modules",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/list",e);
        }
        return result;
    }
}
